<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: luchao@clcw.com.cn                                             |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Other;

use AuctionCore\Common\AntNest;
use AuctionCore\System\AuctionException;
use AuctionCore\Common\PhpRedis;

/**
 * 运营平台 
 * @author      luchao
 */
class Raffle
{


    // private $raffle_type = '';
    // public function __construct($type)
    // {
    //     $this->raffle_type = $type;
    // }

    /**
     * 添加活动
     */
    public function add($sets)
    {
        $data = array();
        $data['a_name'] = $sets['a_name'];
        $data['amount'] = $sets['amount'];
        $data['emp_id'] = $sets['emp_id'];
        $data['type'] = $this->raffle_type;
        $data['starttime'] = $sets['start_date'];
        $data['endtime'] = $sets['end_date'];
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['denomination'] = $sets['denomination'];
        $id = M('activity')->add($data);
            //修改
        M('activity')->where("aid='" . $id . "'")->save(array('activity_no' => $id + 100000000));
        return $id;
    }
    /**
     * 获取指定活动信息
     * @return   Array
     */
    public function search_one($aid)
    {
        return M('activity')->where("aid=".$aid)->find();
    }

    /**
     * 修改指定活动信息
     * @return  
     */
    public function update_one($eidt,$aid){
        return M('activity')->where("aid=".$aid)->save($eidt);
    }

    /**
     * 给指定的订单绑定卡券
     * @return   
     */
    public function order_binding_card($order_id){
        $nowdate = date("Y-m-d H:i:s");
        //时间内有没有活动
        $aid = $this->is_have_activity($nowdate);
        //有活动- 求活动下所有面值的数量
        if ($aid) {
            //找到活动下各种面值的奖券对应的数量 返回二维数组
            $arr_num = $this->get_denomination_type($aid);
            // $num = $this->not_gave_card_num($aid);
            //随机算法 得到一个随机面值
            $price = $this->get_rand_price($arr_num);
            //根据获取随机面额找到一条未分发卡券
            $redis = new PhpRedis();
            //加锁 堵塞
            $key = getRedisKeyByCode('REDIS_KEY','100020');
            $redis->lock_wait($key);
            $cid = $this->get_one_card($price,$aid);
            if ($cid) {
                //把这张卡券绑定订单
                $ok = $this->binding($cid,$order_id);
                $redis->unlock($key); 
            }else{
                //该面值卡券已全部分发出去，递归需要重新去池子里面找
                $redis->unlock($key);    
                $newarr = array();
                foreach ($arr_num as $k => $v) {
                    if ($v['price'] != $price) {
                        $newarr[] = $v;
                    }
                }
                if (count($newarr) < 1) {
                    return 0;
                }
                $ok = $this->again_search($newarr);
                $redis->unlock($key);
            }

        }else{

        }
        return  $ok;
    }

    /**
     * 该面值卡券已全部分发出去，需要重新去池子里面找
     * @return  
     */
    private function again_search($arr){
        $key = getRedisKeyByCode('REDIS_KEY','100020');
        $redis = new PhpRedis();
        $price = $this->get_rand_price($arr);
        //根据获取随机面额找到一条未分发卡券
        $redis->lock_wait($key);
        $cid = $this->get_one_card($price,$aid);
        if ($cid) {
            //把这张卡券绑定订单
            $ok = $this->binding($cid,$order_id);
            $redis->unlock($key);
            return  $ok;
        }else{
            $redis->unlock($key);
            $newarr = array();
            foreach ($arr as $k1 => $v1) {
                if ($v1['price'] != $price) {
                    $newarr[] = $v1;
                }
            }
            if (count($newarr) < 1) {
                return 0;
            }
            return $this->again_search($newarr);
            
        }
    }

    /**
     * 根据获取随机面试找到一条卡券
     * @return  array 卡券id
     */
    private function get_one_card($price,$aid){
        $where = array();
        $where['price'] = array('eq',$price);
        $where['order_id'] = array('eq',0);
        $where['a_id'] = array('eq',$aid);
        $one_card =  M('scratch_card')->field('cid')->where($where)->find();
        return $one_card;
    }

    /**
     * 获取指定活动下所有类型卡卷的数量
     * @return  array  
     */
    public function get_denomination_type($aid){
        $where['a_id'] = array('eq',$aid);
        return M('scratch_card')->field('count(*) as num,price')->where($where)->group('price')->select();
    }


    /**
     * 获取指定活动下卡卷数量 余额 
     * @return  array 
     */
    public function get_num_balance($aid){
        $where['aid'] = array('eq',$aid);
        $map['a_id'] = array('eq',$aid);
        //活动总额
        $amount = M('activity')->field('amount')->where($where)->find();
        $denomination_num = M('scratch_card')->field('count(*) as num,price')->where($map)->group('price')->select();
        if (!empty($denomination_num)) {
            $denomination_num[0]['balance'] = $amount['amount'];
        }
        $newarr = array();
        foreach ($denomination_num as $key => $value) {
            $newarr[$key]['num'] = $value['num'];
            $newarr[$key]['price'] = $value['price'];
            if ($key == 0) {
                $newarr[$key]['balance'] = $value['balance'];
            }else{
                $newarr[$key]['balance'] = $newarr[$key-1]['balance'] - ($newarr[$key-1]['num']*$newarr[$key-1]['price']);
            }
        }
        return $newarr;
    }


    /**
    * 随机算法 有点恶心
    * @return  String 随机出来的面额
    **/
    private function get_rand_price($arr_num){
        //各种面额算出总数
        $allnum = 0;
        foreach ($arr_num as  $value) {
            $allnum += $value['num'];
        }
        $aaa = array();
        $i = 0;
        foreach ($arr_num as  $v) {
            $aaa[$i]['a_num'] = ceil(($v['num']/$allnum)*10000);
            $aaa[$i]['price'] = $v['price'];
            $i++;
        }
        $bbb = array();
        //各种面额闭合区间
        foreach ($aaa as $k1 => $v1) {
            $bbb[$k1]['start_num'] = 1+$bbb[$k1-1]['end_num'];
            $bbb[$k1]['end_num'] = $v1['a_num'] + $bbb[$k1-1]['end_num'];
            $bbb[$k1]['price'] = $v1['price'];
        }
        //随机1-10000区间的数
        $id = rand(1,10000);
        $type = "";
        foreach ($bbb as $k2 => $v2) {
            if ($id > $v2['start_num'] && $id < $v2['end_num']) {
                    return $v2['price'];
            }
        }
    }
    /**
     * 当前时间有没有抽奖活动
     * @return  int 活动id
     */
    private function is_have_activity($nowdate){
        $where = array();
        $where['starttime'] = array("elt",$nowdate);
        $where['endtime'] = array("egt",$nowdate);
        $aid = M('activity')->field('aid')->where($where)->order("createtime desc")->find();
        return $aid['aid'];
    }
    /**
     * 没有发放卡券数量
     * @return  
     */
    private function not_gave_card_num($aid){
        $where = array();
        $where['order_id'] = array('eq',0);
        $where['a_id'] = array('eq',$aid);
        $prefix = C('DB_PREFIX');
        $total = M('scratch_card')->where($where)->count();
        return $total;
    }

     /**
     *  给卡券绑定订单 
     * @return  int
     */
     private function binding($cid,$order_id){
        $ok = M('scratch_card')->where(array('cid'=>$cid['cid']))->save(array('order_id'=>$order_id));
        return $ok;
     }

    /** 
     *  活动类型为抽代金券 1:更新奖券抽奖时间，奖券状态state=1;
     *                   2:根据面额生成一条或者多条代金券;au_coupon
     *                   3:根据面额给车商分配一条或者多条代金券;au_dealer_coupon
     *                   4:奖券对应代金券表数据;au_lottery_coupon
     *  活动类型为抽奖立减：只需更新奖券抽奖时间，奖券状态state=1;
     * @return  string 订单对应卡券的面额
     **/
     public function return_face_value($order_id,$type){
        $map['c.order_id'] = $order_id;
        $map['a.type'] = $type;
        $prefix = C('DB_PREFIX');
        $card_info = M('scratch_card')->alias('c')->field("c.cid,c.price,a.type,a.starttime,a.coupon_end_date,ct.coupon_type_id,ct.type_name coupon_type_name,a.branch_id")
                ->join('left join '.$prefix."activity a  ON c.a_id = a.aid")
                ->join('left join '.$prefix."coupon_type ct  ON ct.a_id = a.aid")
                ->where($map)->find();
        $result_data = array();
        $dealer = M('dealer_auctioned')->where(array('order_id'=>$order_id,'status'=>0))->find();
        if ($type == 2) {
            M()->startTrans();
            //更新奖券状态以及抽奖时间
            $ok = M('scratch_card')->where(array('cid'=>$card_info['cid']))->save(array('state'=>1,'adopttime'=>date("Y-m-d H:i:s")));
            $coupon_ids = array();
            $dealer_coupon_ids = array();
            $lottery_coupon_ids = array();
            $result_data['total_price'] = $card_info['price'];
            if ($card_info['price']>=500 && $card_info['price']%500 == 0) {
                $num = $card_info['price']/500;
                for ($i = 0; $i<$num; $i++) {
                    $data = array();
                    $dealer_data = array();
                    $lottery_coupon = array();
                    //根据面额生成一条或者多条代金券
                    $data['coupon_type_id'] = $card_info['coupon_type_id'];
                    $data['assign_status'] = 1;
                    $data['start_date'] = $card_info['starttime'];
                    $data['end_date'] = $card_info['coupon_end_date'];
                    $data['createtime'] = date('Y-m-d H:i:s');
                    $data['grant_type'] = 2;
                    $data['branch_company'] = $card_info['branch_id'];
                    $data['amount'] = 500;
                    $id = M('coupon')->add($data);
                    M('coupon')->where("coupon_id='" . $id . "'")->save(array('coupon_no' => $id + 100000000));
                    $coupon_ids[] = $id;
                    //根据面额给车商分配一条或者多条代金券
                    $dealer_data['dealer_id'] = $dealer['dealer_id'];
                    $dealer_data['coupon_id'] = $id;
                    $dealer_data['coupon_no'] = $id + 100000000;
                    $dealer_data['amount'] = 500;
                    $dealer_data['createtime'] = date('Y-m-d H:i:s');
                    $dealer_data['start_date'] = $card_info['starttime'];
                    $dealer_data['end_date'] = $card_info['coupon_end_date'];
                    $dealer_data['coupon_type_id'] = $card_info['coupon_type_id'];
                    $dealer_data['coupon_type_name'] = $card_info['coupon_type_name'];
                    $dealer_data['use_status'] = 0;
                    $dealer_coupon_id = M('dealer_coupon')->add($dealer_data);
                    $dealer_coupon_ids[] = $dealer_coupon_id;

                    $result_data['list'][] = array('name'=>$id + 100000000,'value'=>500);
                    //奖券对应代金券表数据
                    $lottery_coupon['card_id'] = $card_info['cid'];
                    $lottery_coupon['coupon_id'] = $id;
                    $lottery_coupon['createtime'] = date('Y-m-d H:i:s');
                    $lottery_coupon_id = M('lottery_coupon')->add($lottery_coupon);
                    $lottery_coupon_ids[] = $lottery_coupon_id;
                }
            }elseif ($card_info['price']>0 && $card_info['price']<500){
                    $data = array();
                    $dealer_data = array();
                    $lottery_coupon = array();
                    //根据面额生成一条或者多条代金券
                    $data['coupon_type_id'] = $card_info['coupon_type_id'];
                    $data['assign_status'] = 1;
                    $data['start_date'] = $card_info['starttime'];
                    $data['end_date'] = $card_info['coupon_end_date'];
                    $data['createtime'] = date('Y-m-d H:i:s');
                    $data['grant_type'] = 2;
                    $data['branch_company'] = $card_info['branch_id'];
                    $data['amount'] = $card_info['price'];
                    $id = M('coupon')->add($data);
                    M('coupon')->where("coupon_id='" . $id . "'")->save(array('coupon_no' => $id + 100000000));
                    $coupon_ids[] = $id;
                    //根据面额给车商分配一条或者多条代金券
                    $dealer_data['dealer_id'] = $dealer['dealer_id'];
                    $dealer_data['coupon_id'] = $id;
                    $dealer_data['coupon_no'] = $id + 100000000;
                    $dealer_data['amount'] = $card_info['price'];
                    $dealer_data['createtime'] = date('Y-m-d H:i:s');
                    $dealer_data['start_date'] = $card_info['starttime'];
                    $dealer_data['end_date'] = $card_info['coupon_end_date'];
                    $dealer_data['coupon_type_id'] = $card_info['coupon_type_id'];
                    $dealer_data['coupon_type_name'] = $card_info['coupon_type_name'];
                    $dealer_data['use_status'] = 0;
                    $dealer_coupon_id = M('dealer_coupon')->add($dealer_data);
                    $dealer_coupon_ids[] = $dealer_coupon_id;

                    //奖券对应代金券表数据
                    $lottery_coupon['card_id'] = $card_info['cid'];
                    $lottery_coupon['coupon_id'] = $id;
                    $lottery_coupon['createtime'] = date('Y-m-d H:i:s');
                    $lottery_coupon_id = M('lottery_coupon')->add($lottery_coupon);
                    $lottery_coupon_ids[] = $lottery_coupon_id;
                    $result_data['list'][] = array('name'=>$id + 100000000,'value'=>$card_info['price']);
            }
            if ($ok < 1 || empty($lottery_coupon_ids) || empty($dealer_coupon_ids) || empty($coupon_ids)) {
                M()->rollback();
                $result = '失败';
            }else{
                M()->commit();
                $result = '成功';
            } 
        }else{
            $ok = M('scratch_card')->where(array('cid'=>$card_info['cid']))->save(array('state'=>1,'adopttime'=>date("Y-m-d H:i:s")));
            if ($ok < 1) {
                $result = '失败';
            }else{
                $result = '成功';
                $result_data['total_price'] = $card_info['price'];
            }
        }
        // $log = array('emp_id' => , 'action' => '车商抽奖活动-抽奖类型:' .$type . ',车商:' . $dealer['dealer_id'] . ' 结果：' . $result);
        // \AuctionCore\System\SystemLog::add($log);
        return $result_data;
    }


   /**
     * 修改卡券状态改成已使用 use_state = 1
     * @return  
     **/
     public function card_change_state($order_id,$type){
        $map = array();
        $ok = 0;
        $map['c.order_id'] = array('eq',$order_id);
        $map['a.type'] = array('eq', $type);
        $prefix = C('DB_PREFIX');
        $card_info = M('scratch_card')->alias('c')->field("c.cid")
                ->join('left join '. $prefix."activity a  ON c.a_id = a.aid")->where($map)->find();
        if ($card_info) {
            $newmap = array();
            $newmap['cid'] = array('eq',$card_info['cid']);
            $ok = M('scratch_card')->where($newmap)->save(array('use_state'=>1));
        }
        return $ok;
     }

    /**
     *  获取卡券信息
     * @param $map array 条件
     * @return  array
     */
     public function find_cards($map){
        $card_info = M('scratch_card')->where($map)->select();
        return $card_info;
     }

     /**
     *  获取卡券 活动信息
     * @param $order_id $type 拍单id 活动类型
     * @return  array
     */
     public function find_card_activity($order_id,$type){
        $map = array();
        $map['c.order_id'] = $order_id;
        $map['a.type'] = $type;
        $prefix = C('DB_PREFIX');
        $card_info = M('scratch_card')->alias('c')->field("c.*,a.aid,a.a_name,a.type,a.starttime,a.endtime")
                ->join("left join " .$prefix."activity a  ON c.a_id = a.aid")
                ->where($map)->find();
        return $card_info;
     }
    /**
     *  获取活动表中的面值限制
     * @return   array
     */
    public function get_denomination($aid){
        $denomination = M('activity')->field('denomination')->where(array('aid'=>$aid))->find();
        return json_decode($denomination['denomination'],true);
    }


     //生成活动卡券
    public function create_card($aid,$num,$price){
        for ($i=1; $i <= $num ; $i++) {
            $data['a_id'] = $aid;
            $data['price'] = $price;
            $data['createtime'] = date('Y-m-d H:i:s');
            $id = M('scratch_card')->add($data);
            M('scratch_card')->where("cid='" . $id . "'")->save(array('card_no' => $id + 100000000));
        }
    }

    /**
     *  来拍车 获取正在进行中活动车商手机,卡券面额
     * @return   array
     */
    public function get_dealer_phone_card($activity_no){
        $map = array();
        $map['c.order_id'] = array('neq',0); 
        $map['c.state'] = array('eq',1); 
        $map['da.status'] = array('eq',0);
        $size = 20;
        $activity_no = explode(',', $activity_no);
        $map['a.activity_no'] = array('in',$activity_no);
        $cols = "c.price,du.uid";
        $prefix = C('DB_PREFIX');
        $info = M('scratch_card')->alias('c')->field($cols)
            ->join($prefix."activity a  ON c.a_id = a.aid")
            ->join($prefix."order o ON o.order_id= c.order_id")
            ->join('left join '.$prefix."dealer_auctioned as da ON da.order_id = o.order_id")
            ->join($prefix."car_dealer as cd ON cd.dealer_id = da.dealer_id")
            ->join($prefix."dealer_user as du ON cd.dealer_id = du.dealer_id")
            ->where($map)->limit($size)->order("c.adopttime desc")->select();
        //蚁巢服务
        $ant = new AntNest();
        foreach($info as $key => $val){
            $user_info = $ant->get_userinfo($val['uid']);
            $info[$key]['contact_mobile'] = $user_info['pwd_mobile'];
        }
        return $info;
    }
    /**
     *  来拍车 找到一条正在进行中的活动id
     * @return   int 活动id
     */
    private function get_activity_id(){
        $nowdate = date('Y-m-d H:i:s');
        $where = array();
        $where['starttime'] = array('elt',$nowdate);
        $where['endtime'] = array('egt',$nowdate);
        $aid = M('activity')->field('aid')->where($where)->find();
        return $aid['aid'];
    }
}

?>